const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/user');
const { authMiddleware } = require('../middleware/auth');

const router = express.Router();

// @route   POST api/auth/register
// @desc    Register a user
// @access  Public
router.post('/register', async (req, res) => {
  const { username, email, password, full_name, phone, address } = req.body;

  try {
    // Check if user already exists
    let user = await User.findByEmail(email);
    if (user) {
      return res.status(400).json({ message: 'User with this email already exists' });
    }

    user = await User.findByUsername(username);
    if (user) {
      return res.status(400).json({ message: 'Username is already taken' });
    }

    // Create user
    const newUser = await User.create({
      username,
      email,
      password,
      full_name,
      phone,
      address
    });

    // Create JWT Payload
    const payload = {
      user: {
        id: newUser.id,
        username: newUser.username,
        is_admin: newUser.is_admin
      }
    };

    // Sign token
    jwt.sign(
      payload,
      process.env.JWT_SECRET,
      { expiresIn: '24h' },
      (err, token) => {
        if (err) throw err;
        res.json({ token });
      }
    );
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   POST api/auth/login
// @desc    Authenticate user & get token
// @access  Public
router.post('/login', async (req, res) => {
  const { username, password } = req.body;
  
  console.log('Login attempt:', { username });

  try {
    // Check for user
    const user = await User.findByUsername(username);
    if (!user) {
      console.log('Login failed: User not found');
      return res.status(400).json({ message: 'Invalid credentials' });
    }
    
    console.log('User found:', { id: user.id, username: user.username });

    // Check password
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      console.log('Login failed: Password mismatch');
      return res.status(400).json({ message: 'Invalid credentials' });
    }
    
    console.log('Password match, generating token');

    // Create JWT Payload
    const payload = {
      user: {
        id: user.id,
        username: user.username,
        is_admin: user.is_admin
      }
    };

    // Sign token
    jwt.sign(
      payload,
      process.env.JWT_SECRET,
      { expiresIn: '24h' },
      (err, token) => {
        if (err) {
          console.error('Token generation error:', err);
          throw err;
        }
        console.log('Login successful, token generated');
        res.json({ token });
      }
    );
  } catch (err) {
    console.error('Login error:', err.message);
    res.status(500).send('Server error');
  }
});

// @route   GET api/auth/user
// @desc    Get logged in user
// @access  Private
router.get('/user', authMiddleware, async (req, res) => {
  try {
    console.log('获取用户信息请求:', { userId: req.user.id });
    
    if (!req.user || !req.user.id) {
      console.error('认证中间件未提供有效的用户ID');
      return res.status(401).json({ message: '无效的用户凭证' });
    }
    
    const user = await User.findById(req.user.id);
    
    if (!user) {
      console.error('用户不存在:', req.user.id);
      return res.status(404).json({ message: '用户不存在' });
    }
    
    console.log('成功获取用户信息:', { id: user.id, username: user.username });
    res.json(user);
  } catch (err) {
    console.error('获取用户信息错误:', err);
    res.status(500).json({ message: '服务器错误', error: err.message });
  }
});

module.exports = router; 